package com.moli.iov.task.jobhandler;

import com.moli.iov.exception.BusinessException;
import com.moli.iov.his.remote.IVehicleTrainTrajectoryRemoteService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.StringUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * <p>
 *  Manual trigger synchronized vehicle trajectory calendar job.
 * </p>
 *
 * @author OAK
 * @version 3.0
 * @since 2019/10/14 19:54 PM.
 */
@Slf4j
@JobHander(value="manualTriggerVehicleTrajectoryJobHandler")
@Component
public class ManualTriggerVehicleTrajectoryJobHandler extends IJobHandler {

    @Autowired
    private IVehicleTrainTrajectoryRemoteService vehicleTrainTrajectoryRemoteService;

    /**
     * Synchronized vehicle train trajectory.
     * @param param handler argument.
     * @return Whether success status code.
     * @throws Exception exception.
     */
    @Override
    public ReturnT<String> execute(String... param) throws Exception {
        try{
            if(StringUtil.isBlank(param[0])){
                throw new BusinessException("Not found manual trigger to synchronized vehicle trajectory calendar in parameter.");
            }
            int i = Integer.parseInt(param[0]) + 1;
            log.info(" Execute manual trigger to synchronized vehicle trajectory calendar in parameter : {}", param);
            Instant endTime = Instant.now(),
                    startTime;
            while(i > 0) {
                endTime = endTime.minus(i--, ChronoUnit.DAYS);
                startTime = endTime.minus(1, ChronoUnit.DAYS);
                RestResponse<String> restResponse = vehicleTrainTrajectoryRemoteService.executeBatchGenericVehicleTrajectories(startTime, endTime);
            }
            log.info(" Execute manual trigger to synchronized vehicle trajectory calendar success.");
            return ReturnT.SUCCESS;
        }catch (Exception e){
            log.error("Execute manual trigger to synchronized vehicle trajectory calendar found a fail, {}", e);
            return ReturnT.FAIL;
        }
    }
}